#!/usr/bin/env python3

#ln -s $PWD/client.py /usr/local/bin/zlm2

import requests
import json
import sys
import time
import curses
import os
import signal
import configparser
from prettytable import PrettyTable

class StreamItem:
    def __init__(self) -> None:
        self.id: int = 0
        self.app: str
        self.stream: str
        self.origin: str
        self.aliveSecond: int
        self.bytesSpeed: int
        self.schema: str = ""
        self.hls: bool
        self.mp4: bool
        self.type: str
        self.readers: int
        self.tracks: int
        self.width: int
        self.height: int = 0
        self.codec_video: str = ""
        self.codec_audio: str = ""
        self.gop: int
        self.fps: int

    def toSimpleRow(self):
        return [self.id, self.app + "/" + self.stream, self.schema, self.aliveSecond, "{:.1f}Mb".format(self.bytesSpeed), self.type,
                self.readers, self.codec_audio, self.codec_video, self.fps, self.gop, self.width, self.height, self.mp4, self.hls]

    def toFullRow(self):
        return [self.id, self.app + "/" + self.stream,  self.origin, self.schema, self.aliveSecond, "{:.1f}Mb".format(self.bytesSpeed), self.type,
                self.readers, self.codec_audio, self.codec_video, self.fps, self.gop, self.width, self.height, self.mp4, self.hls]


if __name__ == "__main__":
    args = sys.argv
    full_row = False
    run = True
    
    script_path = os.path.abspath(__file__)
    if os.path.islink(script_path):
        real_path = os.path.realpath(script_path)
        ini_dir = os.path.dirname(real_path)
    else:
        ini_dir = os.path.dirname(script_path)
    ini_path = os.path.join(ini_dir,"config.ini")
    
    if not os.path.exists(ini_path):
        ini_path = os.path.join(os.path.dirname(ini_dir),"config.ini") 

    if len(args) > 1:
        if args[1] == "--full":
            full_row = True

    zlm_base_url = "http://127.0.0.1:{}/index/api/getMediaList"
    config = configparser.ConfigParser()
    config.read(ini_path)
    secret = config.get("api", "secret")
    port = config.get("http", "port")
    zlm_base_url = zlm_base_url.format(port)

    screen = curses.initscr()
    curses.noecho()
    screen.nodelay(True)
    curses.curs_set(0)

    def signal_handler(sig, frame):
        global run
        run = False
        curses.nocbreak()
        screen.keypad(False)
        curses.echo()
        curses.curs_set(1)
        curses.endwin()

    signal.signal(signal.SIGINT, signal_handler)

    while run:
        try:
            params = {
                "vhost": "__defaultVhost__",
                "secret": secret,
                # "schema": "rtsp",
                "app": "proxy",
            }

            response = requests.get(zlm_base_url, params=params)

            table = PrettyTable()
            if full_row:
                table.field_names = ["id", "path", "origin", "schema", "duration", "bytesSpeed", "type",
                                     "readers", "audio", "video", "fps", "gop", "width", "height", "mp4", "hls"]
            else:
                table.field_names = ["id", "path", "schema", "duration", "bytesSpeed", "type",
                                     "readers", "audio", "video", "fps", "gop", "width", "height", "mp4", "hls"]

            if response.status_code == 200:
                doc = json.loads(response.text)
                if doc["code"] == 0:
                    for i, stream in enumerate(doc["data"]):
                        item = StreamItem()
                        item.id = i+1
                        item.app = stream["app"]
                        item.stream = stream["stream"]
                        item.bytesSpeed = stream["bytesSpeed"] * \
                            8 / 1024.0 / 1024.0
                        item.hls = stream["isRecordingHLS"]
                        item.mp4 = stream["isRecordingMP4"]
                        item.type = stream["originTypeStr"]
                        item.origin = stream["originUrl"]
                        item.schema = stream["schema"]
                        item.readers = stream["readerCount"]
                        item.aliveSecond = stream["aliveSecond"]

                        for track in stream["tracks"]:
                            if track["codec_type"] == 1:
                                item.codec_audio = track["codec_id_name"]

                            if track["codec_type"] == 0:
                                item.codec_video = track["codec_id_name"]
                                item.fps = track["fps"]
                                item.gop = track["gop_size"]
                                item.height = track["height"]
                                item.width = track["width"]

                        # print(item.__dict__)
                        table.add_row(item.toFullRow()
                                      if full_row else item.toSimpleRow())

            screen.clear()
            screen.addstr(table.get_string())
            screen.refresh()

        except Exception as e:
            screen.clear()
            screen.addstr(str(e))
            screen.refresh()

        finally:
            time.sleep(1)
            c = screen.getch()
            if c == ord("q") or c == ord("Q") or c == 3:  # 3 表示 Ctrl+C
                break
    # 恢复终端设置
    curses.nocbreak()
    screen.keypad(False)
    curses.echo()
    curses.curs_set(1)
    curses.endwin()
